package main

import (
	"github.com/graarh/golang-socketio"
	"github.com/graarh/golang-socketio/transport"
	"log"
	"net/http"
	"snowman_api/models"
)

type Message struct {
	Id      int    `json:"id"`
	Channel string `json:"channel"`
	Text    string `json:"text"`
}

func main() {

	server := gosocketio.NewServer(transport.GetDefaultWebsocketTransport())

	server.On(gosocketio.OnConnection, func(c *gosocketio.Channel) {

		log.Println("Connected", server.AmountOfSids())
	})
	server.On(gosocketio.OnDisconnection, func(c *gosocketio.Channel) {
		log.Println("Disconnected")
		c.Close()
	})

	//handle join event
	server.On("join", func(c *gosocketio.Channel, msg models.JoinMsg) string {
		//send event to all in room
		log.Println("join room")
		c.Join(msg.Room)
		c.BroadcastTo(msg.Room, "dojoin", msg)
		return ""
	})
	//handle leave event
	server.On("leave", func(c *gosocketio.Channel, msg models.JoinMsg) string {
		//send event to all in room
		log.Println("leave room")
		c.Leave(msg.Room)
		c.BroadcastTo(msg.Room, "doleave", msg)
		return ""
	})

	//handle action event
	server.On("action", func(c *gosocketio.Channel, msg models.ActionMSG) string {
		//send event to all in room
		log.Println("action room")
		c.Emit("doaction", msg) // for test
		//c.BroadcastTo(msg.Room, "doaction", msg)
		return ""
	})

	serveMux := http.NewServeMux()
	serveMux.Handle("/socket.io/", server)
	serveMux.HandleFunc("/", homePage)

	log.Println("Starting server...")
	log.Panic(http.ListenAndServe(":5000", serveMux))
}

func homePage(res http.ResponseWriter, req *http.Request) {
	http.ServeFile(res, req, "index.html")
}
